<!-- FileImport.vue -->
<template>
  <div>
    <el-upload
      class="upload-demo"
      action=""
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :file-list="fileList"
      multiple
      :limit="3"
      :on-exceed="handleExceed"
      :auto-upload="false"
      drag
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">Drag or click to upload files</div>
      <div v-if="fileList.length >= 3" class="el-upload__tip">Only jpg/png files with a size less than 500KB</div>
    </el-upload>
    <el-button type="primary" @click="submitUpload">Submit Upload</el-button>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";

const fileList = ref([]);

const beforeUpload = (file) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 0.5;

  if (!isJPG && !isPNG) {
    ElMessage.error("You can only upload JPG/PNG file!");
  }
  if (!isLt2M) {
    ElMessage.error("The image size cannot exceed 500KB!");
  }
  return isJPG || (isPNG && isLt2M);
};

const handleSuccess = (response, file, fileList) => {
  ElMessage.success(`${file.name} file uploaded successfully`);
};

const handleError = (err, file, fileList) => {
  ElMessage.error(`${file.name} file upload failed`);
};

const handleExceed = (files, fileList) => {
  ElMessage.warning(`The limit of ${fileList.length + files.length} files has been exceeded!`);
};

const submitUpload = () => {
  const validFiles = fileList.value.filter((file) => file.status === "ready");
  if (validFiles.length === 0) {
    ElMessage.warning("Please select files to upload!");
    return;
  }
  // Here you can implement the actual upload logic, e.g., using FormData and axios
  // For now, just simulate a successful upload
  validFiles.forEach((file) => {
    file.status = "uploading";
    // Simulate upload process
    setTimeout(() => {
      file.status = "success";
      ElMessage.success(`${file.name} file uploaded successfully`);
    }, 1000);
  });
};
</script>

<style scoped>
.upload-demo {
  display: inline-block;
  width: 360px;
  height: 180px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  text-align: center;
  cursor: pointer;
  position: relative;
}
.upload-demo i {
  font-size: 28px;
  color: #99a9bf;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.upload-demo .el-upload__text {
  color: #666;
  font-size: 14px;
  margin-top: 10px;
}
.el-upload__tip {
  font-size: 12px;
  color: #666;
}
</style>
